package com.zhz.leetcode;

public class Test {
    public static void main(String[] args) {
        Test m = new Test();
        int a = m.myAtoi("-5-");
        System.out.println(a);
    }

    public int myAtoi(String s) {
        char[] arr = s.toCharArray();
        int res = 0;
        boolean isFu = false;
        boolean hasFu = false;
        boolean hasNum = false;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= '0' && arr[i] <= '9') {
                hasNum = true;
                int tmp = isFu ? -res : res;
                if (tmp > Integer.MAX_VALUE / 10 || (tmp == Integer.MAX_VALUE / 10 && Integer.MAX_VALUE % 10 <= arr[i] - '0')) {
                    return Integer.MAX_VALUE;
                }
                if (tmp < Integer.MIN_VALUE / 10 || (tmp == Integer.MIN_VALUE / 10 && Integer.MIN_VALUE % 10 > -(arr[i] - '0'))) {
                    return Integer.MIN_VALUE;
                }
                res = res * 10 + (arr[i] - '0');
            } else if (arr[i] == '+' || arr[i] == '-') {
                if (hasFu || hasNum) {
                    return isFu ? -res : res;
                }
                hasFu = true;
                isFu = arr[i] == '-';
            } else if (arr[i] != ' ' || (hasNum || hasFu)) {
                break;
            }
        }
        return isFu ? -res : res;
    }

}
